package com.ssdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssdp.constant.RedisConstant;
import com.ssdp.dto.Result;
import com.ssdp.dto.UserDTO;
import com.ssdp.entity.Follow;
import com.ssdp.entity.User;
import com.ssdp.mapper.FollowMapper;
import com.ssdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssdp.service.IUserService;
import com.ssdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author syo 2319615164@qq.com
 * @description 好友关注服务
 * @date 2024/3/14
 * @Copyright syo
 */
@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private final StringRedisTemplate stringRedisTemplate;

    private final IUserService userService;

    /**
     * 关注和取关
     *
     * @param followUserId 另一用户Id
     * @param isFollow     true为关注，false为取关
     * @return 结果
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstant.FOLLOW_USER_KEY + userId;

        // 1. 判断到底是关注还是取关
        if(isFollow) {
            // 2. 关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if(isSuccess) {
                // 将关注的用户的id放入redis的set集合
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }

        } else {
            // 3. 取关， 删除
            QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
            followQueryWrapper.eq("user_id", userId);
            followQueryWrapper.eq("follow_user_id", followUserId);
            boolean isSuccess = this.remove(followQueryWrapper);
            if(isSuccess) {
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }

        }

        return Result.ok();
    }

    /**
     * 判断是否为当前用户的关注
     * @param followUserId 另一用户的Id
     * @return 结果
     */
    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        // 1. 查询是否关注
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();

        // 2. 如果count值大于0就表明关注了
        return Result.ok(count > 0);
    }

    /**
     * 共同关注
     * @param id 另一个好友的Id
     * @return 结果
     */
    @Override
    public Result followCommons(Long id) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key1 = RedisConstant.FOLLOW_USER_KEY + userId;

        // 2. 获取目标用户
        String key2 = RedisConstant.FOLLOW_USER_KEY + id;

        // 3. 求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if(intersect == null || intersect.isEmpty()) return Result.ok(Collections.emptyList());

        // 4. 解析id
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        // 5. 查询用户
        List<User> users = userService.listByIds(ids);

        List<UserDTO> userDTOS  = users.stream().map(item -> {
            return BeanUtil.copyProperties(item, UserDTO.class);
        }).collect(Collectors.toList());


        return Result.ok(userDTOS);
    }
}
